<template>
    <div class="login-page">
        <div>
            <van-icon name="arrow-left" color="#fff" class="back_img" @click="back"></van-icon>
            <div class="text1">欢迎使用种业通APP</div>
            <div class="text2">登录账号，即刻开始使用</div>
        </div>

        <van-tabs class="custom-tabs tabs1" v-model:active="activeTab" :border="false">
            <van-tab title="账号登录" :border="false">
                <van-cell-group :border="false">
                    <van-field class="field1" center v-model="username" placeholder="请输入账号名称"
                        :left-icon="usernameIcon" />
                    <van-field class="field1" center :left-icon="userpwdIcon" v-model="password"
                        :type="showPassword ? 'text' : 'password'" placeholder="密码"
                        :right-icon="showPassword ? 'eye-o' : 'closed-eye'"
                        @click-right-icon="showPassword = !showPassword" />
                    <div class="forgot-password" @click="forgotPassword">忘记密码?</div>
                    <div style="margin: 16px; margin-top: 32px;">
                        <van-button type="primary" round block @click="pwd_login"
                            color="linear-gradient(to right, #00BF87, #25F0A0)">登 录</van-button>
                    </div>
                    <div style="text-align: center; font-size: 13px; margin-top: 28px;"><span
                            style="color: #AAAAAA;">还没有账号？</span><span @click="register"
                            style="color: #16CE8A;">立即注册</span></div>
                </van-cell-group>
            </van-tab>
            <van-tab title="手机登录" :border="false">
                <van-cell-group :border="false">
                    <van-field class="field1" v-model="userphone" center :left-icon="userphoneIcon" placeholder="请输入手机号"
                        type="tel" maxlength="11" />
                    <van-field class="field1" v-model="validCode" center :left-icon="userpwdIcon" placeholder="请输入短信验证码"
                        type="number" maxlength="4">
                        <template #button>
                            <van-button type="primary" round style="height: 25px; " :style="buttonStyle" :color="clocr"
                                :text="codebtn" @click="getVerificationCode" />
                        </template>
                    </van-field>
                    <div class="forgot-password" @click="forgotPassword">忘记密码?</div>

                    <div style="margin: 16px; margin-top: 32px;">
                        <van-button type="primary" round block @click="phone_login"
                            color="linear-gradient(to right, #00BF87, #25F0A0)">登
                            录</van-button>
                    </div>
                    <div style="text-align: center; font-size: 13px; margin-top: 28px;">
                        <span style="color: #AAAAAA;">还没有账号？</span>
                        <span @click="register" style="color: #16CE8A;">立即注册</span>
                    </div>
                </van-cell-group>
            </van-tab>
        </van-tabs>

        <PhoneLoginListPopup :show="showPhoneList" :dataValue="phoneUser" @update:show="showPhoneList = $event"
            @data-selected-click="data => selectUser(data)" />
        <RegisterView :show="showReg" @update:show="showReg = $event" />
        <WangJiMiMaView :show="showWjmm" @update:show="showWjmm = $event" />
        <XiuGaiMiMaView :show="showXgmm" @update:show="showXgmm = $event" />
    </div>
</template>

<script setup>
import "@/assets/css/tabs.css"
import { ref, computed, onBeforeUnmount } from 'vue';
import usernameIcon from '@/assets/img/login_user.png';
import userpwdIcon from '@/assets/img/login_pwd.png';
import userphoneIcon from '@/assets/img/login_phone.png';
import { useRouter } from 'vue-router';
import uiUtil from "@/util/UiUtil.js";
import PhoneLoginListPopup from '@/components/login/PhoneLoginListPopup.vue';
import RegisterView from '@/components/login/RegisterView.vue';
import WangJiMiMaView from '@/components/login/WangJiMiMaView.vue';
import XiuGaiMiMaView from "@/components/login/XiuGaiMiMaView.vue";

const router = useRouter();

const activeTab = ref(0);
// const username = ref('石家庄市春苗种子经营部');
// const password = ref('1234567Aa!');
const username = ref('农业部BA');
const password = ref('NYBzys@5919');
// const username = ref('BA130000');
// const password = ref('HBzz#85697909');
// const username = ref('BA130100');
// const password = ref('pjhGLZ@126');
// const username = ref('BA130108');
// const password = ref('nyk86578763!A');
const userphone = ref('');
const validCode = ref('');
const showPassword = ref(false);
const showPhoneList = ref(false);
const showReg = ref(false);
const showWjmm = ref(false);
const showXgmm = ref(false)
const phoneUser = ref([]);
const clocr = ref('linear-gradient(to right, #00BF87, #25F0A0)');
const codebtn = ref('获取验证码');

const textColor = ref('white');

const buttonStyle = computed(() => {
    return {
        color: textColor.value
    };
});
const pwd_login = () => {

    if (username === null || username.value === null || username.value === '') {
        uiUtil.toast("请输入用户名");
        return
    }
    if (password === null || password.value === null || password.value === '') {
        uiUtil.toast("请输入密码");
        return
    }
    var data = {
        username: username.value,
        password: uiUtil.encrypt(password.value)
    }
    applogin(data)
};


const applogin = (data) => {
    uiUtil.http().postObj({
        url: uiUtil.urlPath.login,
        data: data,
        start: () => {
            uiUtil.toastLoading('加载中...');
        },
        succeed: (res) => {
            if (!res) {
                uiUtil.toastFail('网络超时');
                return
            }
            if (!res || !res.code || 200 != res.code) {
                uiUtil.toastFail(res.msg);
                return
            }
            localStorage.setItem(uiUtil.urlPath.keys.token, res.data.Tokens);
            localStorage.setItem(uiUtil.urlPath.keys.user, JSON.stringify(res.data));
            var un = res.data.UserLoginName
            console.log('uname1======', un)
            localStorage.setItem(uiUtil.urlPath.keys.username, un);
            localStorage.setItem(uiUtil.urlPath.keys.uid, res.data.UserID);
            const token = localStorage.getItem('token')
            const uname = localStorage.getItem(uiUtil.urlPath.keys.username)
            const uid = localStorage.getItem('uid')

            console.log('Authorization-l======', token)
            console.log('uname======', uname, res.data.UserLoginName, localStorage.getItem(uiUtil.urlPath.keys.username))
            console.log('uid======', uid)
            if (password.value && password.value.length < 10 && !uiUtil.containsThreeCategories(password.value)) {
                uiUtil.toast('密码至少包含大、小写字母、数字、特殊字符中的三种');
                showXgmm.value = true
            } else {
                uiUtil.toastClose();
                router.push({ path: uiUtil.routerPath.main });
            }
        },
        failed: (err) => {
            // debugger;
            uiUtil.toastFail('登录失败：' + err);
        },
        finish: (type) => {
            // debugger;
            console.log('finish=', type)
            // uiUtil.toastClose();
        }
    })
};


const selectUser = (item) => {

    var data = {
        username: item.userLoginName,
        password: item.userPassword,
    }
    applogin(data)
}

const phone_login = () => {
    if (userphone === null || userphone.value === null || userphone.value === '' || userphone.value.length < 11) {
        uiUtil.toast("请输入正确的手机号");
        return
    }
    if (validCode === null || validCode.value === null || validCode.value === '') {
        uiUtil.toast("请输入验证码");
        return
    }
    console.log('获取验证码', userphone.value);
    //http://114.242.25.97:20167/api/seedarchive/sms/sendValidCode
    countdown.value = 0
    // 获取验证码操作
    const data = {
        linkmanPhone: userphone.value,
        validCode: validCode.value,
    }
    uiUtil.http().postObj({
        url: uiUtil.urlPath.phonelogin,
        data: data,
        start: () => {
            uiUtil.toastLoading('加载中...');
        },
        succeed: (res) => {
            if (!res) {
                uiUtil.toastFail('网络超时');
                return
            }
            if (!res || !res.code || 200 != res.code) {
                uiUtil.toastFail(res.msg);
                return
            }
            uiUtil.toastClose();
            if (res && res.data && res.data.length > 0) {
                if (res.data.length == 1) {
                    selectUser(res.data[0])
                } else {
                    showPhoneList.value = true
                    phoneUser.value = res.data
                }
            }

        },
        failed: (err) => {
            uiUtil.toastFail('登录失败：' + err);
        },
        finish: (type) => {
            console.log('finish=', type)
            // uiUtil.toastClose();
        }
    })
};

const forgotPassword = () => {
    showWjmm.value = true
};

const register = () => {
    showReg.value = true
};
const back = () => {
    if (window.history.length > 1) {
        router.back();
    } else {
        router.push({ path: '/' });
    }
}
const getVerificationCode = (event) => {
    if (isCounting.value) return; // 防止重复获取验证码
    if (userphone === null || userphone.value === null || userphone.value === '' || userphone.value.length < 11) {
        uiUtil.toast("请输入正确的手机号");
        return
    }
    console.log('获取验证码', userphone.value);
    //http://114.242.25.97:20167/api/seedarchive/sms/sendValidCode
    // 获取验证码操作
    const data = {
        appName: '',
        companyName: '',
        effectiveTime: '3',
        method: '',
        password: '',
        phones: userphone.value,
        templateNo: '',
        username: '',
        verificationCode: '',
        needCheckPhone: true,
    }
    uiUtil.http().postObj({
        url: uiUtil.urlPath.sendValidCode,
        data: data,
        start: () => {
            uiUtil.toastLoading('加载中...');
        },
        succeed: (res) => {
            if (!res) {
                uiUtil.toastFail('网络超时');
                return
            }
            if (!res || !res.code || 200 != res.code) {
                uiUtil.toastFail(res.msg);
                return
            }
            startCountdown()
            uiUtil.toastSuccess(res.data.validcode);
        },
        failed: (err) => {
            uiUtil.toastFail('登录失败：' + err);
        },
        finish: (type) => {
            console.log('finish=', type)
            // uiUtil.toastClose();
        }
    })
};


//倒计时
const countdown = ref(60); // 初始化倒计时为60秒
const isCounting = ref(false); // 是否正在倒计时
let intervalId; // 保存setInterval的ID

const startCountdown = () => {
    if (isCounting.value) return; // 防止重复启动倒计时
    isCounting.value = true;
    countdown.value = 60; // 每次点击按钮时重置倒计时为60秒
    intervalId = window.setInterval(() => {
        if (countdown.value > 1) {
            countdown.value -= 1;
            console.log(countdown.value)
            clocr.value = ('linear-gradient(to right, #F5F5F5, #F5F5F5)');
            textColor.value = ('#AAAAAA')
            codebtn.value = countdown.value + 's后重新发送'
        } else {
            clocr.value = ('linear-gradient(to right, #00BF87, #25F0A0)');
            textColor.value = ('#ffffff')
            codebtn.value = '获取验证码'
            clearInterval(intervalId);
            isCounting.value = false;
        }
    }, 1000); // 每秒钟更新一次倒计时
};
// 清理计时器，当组件卸载时防止内存泄漏 
onBeforeUnmount(() => {
    if (intervalId !== undefined) {
        clearInterval(intervalId);
    }
});
//倒计时结束

</script>

<style scoped>
.login-page {
    background: url('@/assets/img/main/home_bg.png') no-repeat;
    background-size: cover;
}

.back_img {
    padding: 17px;
}

.text1 {
    padding-left: 27px;
    font-size: 24px;
    color: white;
}

.text2 {
    padding-top: 12px;
    padding-left: 27px;
    font-size: 17px;
    color: #ccffffff;
}


.tabs1 {
    padding-top: 60px;
    height: 44px;
    text-align: center;
    align-items: center;
}

.field1 {
    padding-top: 12px;
    min-height: 60px;
    text-align: center;
}

.forgot-password {
    margin: 16px;
    text-align: right;
    color: #AAAAAA;
    cursor: pointer;
}

.van-divider {
    margin: 16px 0;
}

.popup-content {
    padding: 16px;
}

.verification-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.verification-section .van-field__control {
    flex: 1;
}

.verification-section .van-button {
    margin-left: 8px;
}

.left-text {
    color: black;
    cursor: pointer;
}
</style>